package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver;

    public static WebDriver createDriver(){
        if(driver == null){
//            WebDriverManager.chromedriver().setup();
//            ChromeOptions options = new ChromeOptions();

            System.setProperty("webdriver.chrome.driver", "D:/测试/web驱动/chromedriver-win64/chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            //允许访问所有的链接
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            //等待（隐式）
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }

    public Utils(String url){
        //调用 driver 对象
        driver = createDriver();

        //访问 url
        driver.get(url);
    }

    //屏幕截图
    public void getScreenShot(String str) throws IOException {

        //      ./src/test/image/
        //                      /2025-08-06/
        //                                 /test01-17453010.png
        //                                 /test02-17453020.png
        //                      /2025-08-07/
        //                                 /test01-17453030.png
        //                                 /test01-17453034.png
        //屏幕截图
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String filename = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime + ".png";
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

        //srcFile 放到指定位置
        FileUtils.copyFile(srcFile,new File(filename));
    }

}
